package com.leo.sunnyweather.ui.places

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.leo.sunnyweather.R
import com.leo.sunnyweather.logic.model.Place
import kotlinx.android.synthetic.main.fragment_query_places.*

/**
 * A simple [Fragment] subclass.
 * Use the [QueryPlacesFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class QueryPlacesFragment : Fragment() {

    private lateinit var adapter: PlaceQueryResultAdapter

    private val viewModel: PlaceViewModel by lazy { ViewModelProvider(this).get(PlaceViewModel::class.java) }

    companion object {
        @JvmStatic
        fun newInstance() = QueryPlacesFragment()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_query_places, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        adapter = PlaceQueryResultAdapter(this, viewModel.placesList)
        var layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        fragment_query_places_recycler_view.layoutManager = layoutManager
        fragment_query_places_recycler_view.adapter = adapter

        fragment_query_places_edt_input_query.addTextChangedListener { afterText ->
            viewModel.placesList.clear()
            adapter.notifyDataSetChanged()
            val query = afterText.toString()
            fragment_query_places_iv_bg.visibility = View.VISIBLE
            if (query.isNotEmpty()) {
                viewModel.queryPlace(query)
            }
        }

        viewModel.placesLiveData.observe(viewLifecycleOwner, Observer {
            val places = it.getOrNull()
            if (places != null) {
                fragment_query_places_iv_bg.visibility = View.INVISIBLE
                viewModel.placesList.addAll(places)
                adapter.notifyDataSetChanged()
            } else {
                it.exceptionOrNull()?.printStackTrace()
            }
        })

    }
}